﻿using PC_Touch.DataOP;
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.IO;
using System.Linq;
using System.Text;
using System.Text.Json;
using System.Threading.Tasks;
using System.Windows.Forms;
using Sunny.UI;
using System.Diagnostics;
using HslCommunication;
using System.Reflection;

namespace PC_Touch
{
    public partial class Form1 : Form
    {
        public Form1()
        {
            InitializeComponent();
            x = this.Width;
            y = this.Height;
            setTag(this);
            this.Resize += new EventHandler(this.Form_Resize);
            setZH_EN();
        }
        private void setZH_EN()
        {
            if (LanguageHelper.zh_enFlag == "中文")
            {
            }
            else
            {
                uiGroupBox5.Text = "Process value monitoring";
                uiGroupBox1.Text = "PLC state";
                uiGroupBox2.Text = "System state";
                uiGroupBox4.Text = "Test result";
                uiGroupBox3.Text = "Status monitoring";
                uiMarkLabel2.Text = "Test line supply pressure value";
                uiMarkLabel3.Text = "Real-time pump speed";
                uiMarkLabel4.Text = "Real-time flow on the left side";
                uiMarkLabel5.Text = "Real-time flow on the right side";
                uiMarkLabel9.Text = "Left line pre-test pressure value";
                uiMarkLabel8.Text = "Left line Post-test pressure value";
                uiMarkLabel7.Text = "Right line pre-test pressure value";
                uiMarkLabel6.Text = "Right line Post-test pressure value";
            }
        }
        private void IObutton_Click(object sender, EventArgs e)
        {
            IOMonitorSetting iomonitorSetting = new IOMonitorSetting();
            iomonitorSetting.Show();
        }

        private void button1_Click(object sender, EventArgs e)
        {
            IOMonitor iomonitor = new IOMonitor();
            iomonitor.Show();
        }

        private void Form1_Load(object sender, EventArgs e)
        {

            var jsonMachine = JsonSerializer.Deserialize<JsonMachine>(File.ReadAllText(Environment.CurrentDirectory + @"/AppConfig/Machine.Json", Encoding.UTF8));
<<<<<<< HEAD
            string msg = PLCHelper.OpenPLC(jsonMachine.plcIP,103);
=======
            string msg = PLCHelper.OpenPLC(jsonMachine.plcIP);
>>>>>>> 7dcc016849873c89bffdc611d8d2656801e356cd
            if (msg.Contains("success"))
            {
                this.ShowSuccessTip(msg);
            }
            else
            {
                this.ShowErrorTip(msg);
            }
            //监听事件初始化
            //PLCHelper.TriggerEventInit();
            //PLC轮询读取触发信号
           
        }

        private void button3_Click(object sender, EventArgs e)
        {
            TaskManagement taskManagement = new TaskManagement();
            taskManagement.Show();
        }

        #region 控件缩放
        private float x = 1;
        private float y = 1;
        private void setTag(Control cons)
        {
            foreach (Control con in cons.Controls)
            {
                con.Tag = con.Width + ";" + con.Height + ";" + con.Left + ";" + con.Top + ";" + con.Font.Size;
                if (con.Controls.Count > 0)
                {
                    setTag(con);
                }
            }
        }
        private void setControls(float newx, float newy, Control cons)
        {
            foreach (Control con in cons.Controls)
            {
               
                if (con.Tag != null)
                {
                    string[] mytag = con.Tag.ToString().Split(new char[] { ';' });
                    con.Width = Convert.ToInt32(Convert.ToSingle(mytag[0]) * newx);//宽度
                    con.Height = Convert.ToInt32(Convert.ToSingle(mytag[1]) * newy);//高度
                    con.Left = Convert.ToInt32(Convert.ToSingle(mytag[2]) * newx);//左边距
                    con.Top = Convert.ToInt32(Convert.ToSingle(mytag[3]) * newy);//顶边距
                    Single currentSize = Convert.ToSingle(mytag[4]) * newy;//字体大小
                    con.Font = new Font(con.Font.Name, currentSize, con.Font.Style, con.Font.Unit);
                    if (con.Controls.Count > 0)
                    {
                        setControls(newx, newy, con);
                    }
                }
            }
        }
        private void Form_Resize(object sender, EventArgs e)
        {
            float newx = (this.Width) / x;
            float newy = (this.Height) / y;
            setControls(newx, newy, this);
        }
        #endregion

        private void button4_Click(object sender, EventArgs e)
        {
            CollectionConfig collectionConfig = new CollectionConfig();
            collectionConfig.Show();
        }

        private void uiTurnSwitch1_ValueChanged(object sender, bool value)
        {
        }

        private void Form1_FormClosing(object sender, FormClosingEventArgs e)
        {
            if (PLCHelper.siemensConnect.IsSuccess)
            {
                PLCHelper.siemensTcpNet.ConnectClose();
            }
        }

        private void timerJudgement_Tick(object sender, EventArgs e)
        {
            if (PLCHelper.siemensConnect.IsSuccess)
            {
                PLCStatues.State = UILightState.On;
                UISetValue();
            }
            else 
            {
                PLCStatues.State = UILightState.Off;
            }
        }
        private void UISetValue()
        {
           
            if (PLCHelper.siemensConnect.IsSuccess)
            {
                string[] addresses = new string[] { "DB9.54","DB100.90","DB9.58","DB9.62","DB13.8","DB13.12","DB13.0","DB13.4" };
                OperateResult<byte[]> readResult = PLCHelper.siemensTcpNet.Read(addresses, new ushort[] { 4, 4, 4, 4, 4, 4,4,4 });
                if (readResult.IsSuccess)
                {
                    var v1 = PLCHelper.siemensTcpNet.ByteTransform.TransSingle(readResult.Content, 0);
                    测试管路供应压力值.Value = (int)v1;
                    测试管路供应压力值.Text = v1.ToString("F3")+"bar";
                    var v2 = PLCHelper.siemensTcpNet.ByteTransform.TransSingle(readResult.Content, 4);
                    水泵实时转速.Value = (int)v2;
                    水泵实时转速.Text = v2.ToString("F3") + "rpm";
                    var v3 = PLCHelper.siemensTcpNet.ByteTransform.TransSingle(readResult.Content, 8);
                    左侧实时流量.Value = (int)v3;
                    左侧实时流量.Text = v3.ToString("F3") + "m³/h";
                    var v4 = PLCHelper.siemensTcpNet.ByteTransform.TransSingle(readResult.Content, 12);
                    右侧实时流量.Value = (int)v4;
                    右侧实时流量.Text = v4.ToString("F3") + "m³/h";
                    var v5 = PLCHelper.siemensTcpNet.ByteTransform.TransSingle(readResult.Content, 16);
                    左侧管路测试前压力值.Value = (int)v5;
                    左侧管路测试前压力值.Text = v5.ToString("F3") + "bar";
                    var v6 = PLCHelper.siemensTcpNet.ByteTransform.TransSingle(readResult.Content, 20);
                    左侧管路测试后压力值.Value = (int)v6;
                    左侧管路测试后压力值.Text = v6.ToString("F3") + "bar";
                    var v7 = PLCHelper.siemensTcpNet.ByteTransform.TransSingle(readResult.Content, 24);
                    右侧管路测试前压力值.Value = (int)v7;
                    右侧管路测试前压力值.Text = v7.ToString("F3") + "bar";
                    var v8 = PLCHelper.siemensTcpNet.ByteTransform.TransSingle(readResult.Content, 28);
                    右侧管路测试后压力值.Value = (int)v8;
                    右侧管路测试后压力值.Text = v8.ToString("F3") + "bar";
                }
                var Q = PLCHelper.BatchReadPLCIO("Q104", 4);//104 105 106 107

                AV1.State = Q[0, 4] ? UILightState.On:UILightState.Off;
                AV2.State = Q[0, 5] ? UILightState.On : UILightState.Off;
                AV3.State = Q[0, 6] ? UILightState.On : UILightState.Off;
                AV4.State = Q[0, 7] ? UILightState.On : UILightState.Off;
                AV5.State = Q[1, 0] ? UILightState.On : UILightState.Off;
                AV6.State = Q[1, 1] ? UILightState.On : UILightState.Off;
                AV7.State = Q[1, 2] ? UILightState.On : UILightState.Off;
                AV8.State = Q[1, 3] ? UILightState.On : UILightState.Off;
                LV1.State = Q[2, 0] ? UILightState.On : UILightState.Off;
                LV2.State = Q[2, 1] ? UILightState.On : UILightState.Off;
                LV3.State = Q[2, 2] ? UILightState.On : UILightState.Off;
                LV4.State = Q[2, 3] ? UILightState.On : UILightState.Off;
                LV5.State = Q[2, 4] ? UILightState.On : UILightState.Off;
                LV6.State = Q[2, 5] ? UILightState.On : UILightState.Off;
                LV7.State = Q[2, 6] ? UILightState.On : UILightState.Off;
                LV8.State = Q[2, 7] ? UILightState.On : UILightState.Off;
                LV9.State = Q[3, 0] ? UILightState.On : UILightState.Off;
                LV10.State = Q[3, 1] ? UILightState.On : UILightState.Off;
                if (PLCHelper.siemensTcpNet.ReadBool("DB100.40.0").Content)//开始
                {
                    PLCHelper.siemensTcpNet.Write("DB100.40.0",false);
                    uiButton1_Click(null,null);
                }
                if (PLCHelper.siemensTcpNet.ReadBool("DB100.40.1").Content)//结束
                {
                    PLCHelper.siemensTcpNet.Write("DB100.40.1", false);
                    uiButton2_Click(null,null);
                }

            }
            else
            {
                MessageBox.Show("PLC not connect!");
            }
        }
        int index = 0;

        private void uiButton1_Click(object sender, EventArgs e)
        {
            uiLight2.State = UILightState.Blink;
            uiLight3.State = UILightState.Blink;

            uiLight1.State = UILightState.On;
            index = 0;
            UILineOption option = new UILineOption();
            option.ToolTip.Visible = true;
            option.Title = new UITitle();
            option.Title.Text = " ";
            option.Title.SubText = "process state";
            var series = option.AddSeries(new UILineSeries("tensioning force"));
            var series2 = option.AddSeries(new UILineSeries("pressure value (left inlet)"));
            var series3 = option.AddSeries(new UILineSeries("pressure value (left outlet)"));
            var series4 = option.AddSeries(new UILineSeries("pressure value (right inlet)"));
            var series5 = option.AddSeries(new UILineSeries("pressure value (right outlet)"));
            var series6 = option.AddSeries(new UILineSeries("pressure differential (left outlet)"));
            var series7 = option.AddSeries(new UILineSeries("pressure differential (right outlet)"));

            //设置Legend
            option.Legend = new UILegend();
            option.Legend.Orient = UIOrient.Vertical;
            option.Legend.Top = UITopAlignment.Top;
            option.Legend.Left = UILeftAlignment.Right;
           // option.Legend.Style = UILegendStyle.Rectangle;
            option.Legend.AddData("tensioning force");
            option.Legend.AddData("pressure value (left inlet)");
            option.Legend.AddData("pressure value (left outlet)");
            option.Legend.AddData("pressure value (right inlet)");
            option.Legend.AddData("pressure value (right outlet)");
            option.Legend.AddData("pressure differential (left outlet)");
            option.Legend.AddData("pressure differential (right outlet)");

            option.XAxis.Name = "count";
            option.YAxis.Name = "value";

            //设置曲线显示最大点数，超过后自动清理
            series.SetMaxCount(1000);
           

            //设置曲线平滑
            series.Smooth = true;
          

            //坐标轴显示小数位数
            option.XAxis.AxisLabel.DecimalPlaces = 1;
            option.YAxis.AxisLabel.DecimalPlaces = 1;
            LineChart.SetOption(option);
            timer1.Start();
        }
        Random random = new Random();

        private void timer1_Tick(object sender, EventArgs e)
        {
            //LineChart.Option.AddData("value1", index, random.NextDouble() * 10);
            //LineChart.Option.AddData("value2", index, random.NextDouble() * 10);
            //LineChart.Option.AddData("value3", index, random.NextDouble() * 10);
            //LineChart.Option.AddData("value4", index, random.NextDouble() * 10);
            //LineChart.Option.AddData("value5", index, random.NextDouble() * 10);

            if (PLCHelper.siemensConnect.IsSuccess)
            {
                //string[] addresses = new string[] { "DB9.50", "DB4.10" };
                string[] addresses = new string[] { "DB100.122", "DB100.134", "DB100.138", "DB100.142", "DB100.146", "DB100.158", "DB100.162" };
                OperateResult<byte[]> readResult = PLCHelper.siemensTcpNet.Read(addresses, new ushort[] { 4,4,4,4,4,4,4 });
                if (readResult.IsSuccess)
                {
                    var v1 = PLCHelper.siemensTcpNet.ByteTransform.TransSingle(readResult.Content, 0);
                    var v2 = PLCHelper.siemensTcpNet.ByteTransform.TransSingle(readResult.Content, 4);
                    var v3 = PLCHelper.siemensTcpNet.ByteTransform.TransSingle(readResult.Content, 8);
                    var v4 = PLCHelper.siemensTcpNet.ByteTransform.TransSingle(readResult.Content, 12);
                    var v5 = PLCHelper.siemensTcpNet.ByteTransform.TransSingle(readResult.Content, 16);
                    var v6 = PLCHelper.siemensTcpNet.ByteTransform.TransSingle(readResult.Content, 20);
                    var v7 = PLCHelper.siemensTcpNet.ByteTransform.TransSingle(readResult.Content, 24);

                    LineChart.Option.AddData("tensioning force", index, v1);
                    LineChart.Option.AddData("pressure value (left inlet)", index, v2);
                    LineChart.Option.AddData("Pressure value (left outlet)", index, v3);
                    LineChart.Option.AddData("pressure value (right inlet)", index, v4);
                    LineChart.Option.AddData("pressure value (right outlet)", index, v5);
                    LineChart.Option.AddData("Pressure differential (left outlet)", index, v6);
                    LineChart.Option.AddData("Pressure differential (right outlet)", index, v7);

                }
            }

            index++;

            if (index > 2000)
            {
                LineChart.Option.XAxis.SetRange(index - 2000, index + 20);
            }

            LineChart.Refresh();
        }

        private void uiButton2_Click(object sender, EventArgs e)
        {

            uiLight1.State = UILightState.Off;
            uiLight2.State = PLCHelper.siemensTcpNet.ReadBool("Q101.2").Content? UILightState.On: UILightState.Off;
            uiLight3.State = PLCHelper.siemensTcpNet.ReadBool("Q103.2").Content ? UILightState.On : UILightState.Off;

            timer1.Stop();
        }
    }
}
